/**
 * @Description: 用户管理相关API - 基于统一的 http 封装与 mockApi 数据源
 * @Author: lujq
 * @Date: 2025-08-25
 * @LastEditors: lujq
 * @LastEditTime: 2025-08-25 14:15:00
 */

import { http } from './index'
import type { User, ApiResponse } from '@/types'

/**
 * 获取用户列表（支持分页、关键字、角色、状态筛选与排序）
 * @param params 查询参数
 * @returns 分页的用户列表数据
 */
export const getUserList = async (
  params: {
    page?: number
    pageSize?: number
    keyword?: string
    status?: 'active' | 'inactive'
    role?: string
    sortBy?: string
    sortOrder?: 'asc' | 'desc'
  } = {},
) => {
  const queryParams = new URLSearchParams()
  if (params.page) queryParams.append('page', String(params.page))
  if (params.pageSize) queryParams.append('pageSize', String(params.pageSize))
  if (params.keyword) queryParams.append('keyword', params.keyword)
  if (params.status) queryParams.append('status', params.status)
  if (params.role) queryParams.append('role', params.role)
  if (params.sortBy) queryParams.append('sortBy', params.sortBy)
  if (params.sortOrder) queryParams.append('sortOrder', params.sortOrder)

  const response = await http.get<{
    items: User[]
    total: number
    page: number
    pageSize: number
    totalPages: number
  }>(`/users?${queryParams.toString()}`)

  return {
    ...response,
    data: {
      list: response.data.items,
      total: response.data.total,
      page: response.data.page,
      pageSize: response.data.pageSize,
    },
  }
}

/**
 * 获取用户详情
 * @param id 用户ID
 */
export const getUserDetail = (id: string): Promise<ApiResponse<User>> => {
  return http.get(`/users/${id}`)
}

/**
 * 新增用户
 * @param data 用户数据（创建时可附带 password 字段）
 */
export const createUser = (
  data: Omit<User, 'id' | 'createTime' | 'lastLoginTime'> & { password?: string },
): Promise<ApiResponse<User>> => {
  return http.post('/users', {
    ...data,
    status: (data as any).status || 'active',
    lastLoginTime: new Date().toISOString(),
    createTime: new Date().toISOString(),
  })
}

/**
 * 更新用户信息（含角色与权限）
 * @param id 用户ID
 * @param data 待更新字段
 */
export const updateUser = (id: string, data: Partial<User>): Promise<ApiResponse<User>> => {
  return http.put(`/users/${id}`, data)
}

/**
 * 删除用户
 * @param id 用户ID
 */
export const deleteUser = (id: string): Promise<ApiResponse<void>> => {
  return http.delete(`/users/${id}`)
}

/**
 * 批量删除用户
 * @param ids 用户ID集合
 */
export const batchDeleteUsers = (ids: string[]): Promise<ApiResponse<{ deletedCount: number }>> => {
  const queryParams = new URLSearchParams()
  ids.forEach((id) => queryParams.append('ids', id))
  return http.delete(`/users?${queryParams.toString()}`)
}